<template>
  <div class="ai-customer-service-container">
    <!-- 头部 -->
    <div class="ai-header">
      <div class="ai-logo">
        <i class="fa fa-robot text-blue-600 mr-2"></i>
        <h2 class="text-xl font-bold text-gray-800">智慧找房助手</h2>
      </div>
      <div class="ai-status">
        <span class="online-indicator"></span>
        <span class="text-green-600 text-sm">在线客服</span>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="ai-main">
      <!-- 侧边栏 -->
      <div class="ai-sidebar">
        <!-- 功能卡片 -->
        <div class="feature-card bg-blue-50 p-4 rounded-lg shadow-sm mb-4">
          <h3 class="font-bold text-gray-700 mb-2">快速功能</h3>
          <div class="feature-buttons">
            <button 
              v-for="feature in quickFeatures" 
              :key="feature.id"
              class="feature-btn bg-white text-gray-700 hover:bg-blue-100 p-2 rounded-md text-sm mb-2 w-full text-left flex items-center transition-all shadow-sm"
              @click="handleQuickFeature(feature)"
            >
              <i :class="['fa', feature.icon, 'mr-2', feature.id >= 7 ? 'text-red-500' : 'text-blue-500']"></i>
              {{ feature.name }}
              <span v-if="feature.id === 7 && favoriteProperties.length > 0" class="ml-auto bg-red-100 text-red-600 text-xs px-1.5 py-0.5 rounded-full">
                {{ favoriteProperties.length }}
              </span>
            </button>
          </div>
        </div>

        <!-- 热门房源 -->
        <div class="hot-properties bg-white p-4 rounded-lg shadow-sm">
          <h3 class="font-bold text-gray-700 mb-2">热门推荐</h3>
          <div class="property-list">
            <div 
              v-for="property in hotProperties" 
              :key="property.id"
              class="property-item hover:bg-gray-50 p-2 rounded-md cursor-pointer transition-all"
              @click="showPropertyDetail(property)"
            >
              <div class="property-info">
                <h4 class="text-sm font-semibold text-gray-800 truncate">{{ property.title }}</h4>
                <div class="property-meta text-xs text-gray-500 mt-1">
                  <span>{{ property.area }}m²</span>
                  <span class="mx-1">·</span>
                  <span>{{ property.type }}</span>
                </div>
                <div class="property-price text-sm font-bold text-red-500 mt-1">{{ property.price }}万</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 聊天区域 -->
      <div class="ai-chat">
        <!-- 对话历史 -->
        <div class="chat-messages">
          <!-- 欢迎消息 -->
          <div class="message ai-message">
            <div class="message-content">
              <p>👋 您好！我是智慧找房助手，请问有什么可以帮到您？</p>
              <p class="mt-2">您可以告诉我您的需求，如：</p>
              <ul class="mt-1 text-sm space-y-1">
                <li>• 我想找一套两居室的房子</li>
                <li>• 预算300万以内有什么推荐？</li>
                <li>• 海淀区的新房有哪些？</li>
              </ul>
            </div>
          </div>

          <!-- 动态消息 -->
          <div 
            v-for="(message, index) in messages" 
            :key="index"
            :class="['message', message.from === 'ai' ? 'ai-message' : 'user-message']"
          >
            <div class="message-content">
              <p v-if="!message.loading">{{ message.content }}</p>
              <div v-else class="loading-indicator">
                <span class="typing-dots">
                  <span class="dot"></span>
                  <span class="dot"></span>
                  <span class="dot"></span>
                </span>
              </div>
              <div v-if="message.properties && message.properties.length > 0" class="property-recommendations mt-3">
                <h4 class="text-sm font-semibold mb-2 text-gray-700">为您找到以下房源：</h4>
                <div class="properties-grid">
                  <div 
                    v-for="property in message.properties" 
                    :key="property.id"
                    class="property-card bg-white rounded-lg shadow-sm p-2 cursor-pointer hover:shadow-md transition-all"
                    @click="showPropertyDetail(property)"
                  >
                    <div class="property-card-info">
                      <h5 class="text-sm font-semibold text-gray-800 truncate">{{ property.title }}</h5>
                      <div class="property-card-meta text-xs text-gray-500 mt-1">
                        <span>{{ property.area }}m²</span>
                        <span class="mx-1">·</span>
                        <span>{{ property.type }}</span>
                      </div>
                      <div class="property-card-price text-sm font-bold text-red-500 mt-1">{{ property.price }}万</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input-area">
          <!-- 输入工具栏 -->
          <div class="input-toolbar flex items-center justify-between p-2 border-b">
            <div class="toolbar-left">
              <button class="toolbar-btn text-gray-500 hover:text-blue-500 transition-colors">
                <i class="fa fa-history"></i>
              </button>
              <button class="toolbar-btn text-gray-500 hover:text-blue-500 transition-colors" @click="clearChatHistory">
                <i class="fa fa-trash"></i>
              </button>
            </div>
            <div class="toolbar-right">
              <button class="toolbar-btn text-gray-500 hover:text-blue-500 transition-colors">
                <i class="fa fa-question-circle"></i>
              </button>
            </div>
          </div>
          
          <!-- 建议标签 -->
          <div class="suggestions p-2 bg-gray-50 border-b">
            <span 
              v-for="suggestion in suggestions" 
              :key="suggestion"
              class="suggestion-tag bg-white text-sm text-gray-700 px-3 py-1 rounded-full cursor-pointer hover:bg-blue-100 transition-colors mr-2 mb-2 inline-block"
              @click="useSuggestion(suggestion)"
            >
              {{ suggestion }}
            </span>
          </div>

          <!-- 输入框 -->
          <div class="input-container flex items-center p-3">
            <input 
              v-model="inputMessage" 
              type="text" 
              class="flex-1 border rounded-full px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="请输入您的问题，按回车发送..."
              @keyup.enter="sendMessage"
              :disabled="isProcessing"
            >
            <button 
              class="send-button ml-2 bg-blue-500 text-white rounded-full p-2 hover:bg-blue-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              @click="sendMessage"
              :disabled="!inputMessage.trim() || isProcessing"
            >
              <i class="fa fa-paper-plane"></i>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 房源详情模态框 -->
    <div v-if="showDetail" class="modal-overlay" @click.self="closeDetail">
      <div class="modal-content">
        <div class="modal-header flex justify-between items-center pb-2 border-b">
          <h3 class="text-lg font-bold text-gray-800">房源详情</h3>
          <button class="close-button text-gray-500 hover:text-gray-800" @click="closeDetail">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div v-if="selectedProperty" class="modal-body p-4">
          <div class="property-detail-image relative mb-4">
            <img 
              :src="`https://picsum.photos/800/400?random=${selectedProperty.id}`" 
              :alt="selectedProperty.title"
              class="w-full h-64 object-cover rounded-lg"
            >
            <div class="property-tags">
              <span v-for="tag in selectedProperty.tags" :key="tag" class="tag bg-blue-500">
                {{ tag }}
              </span>
            </div>
          </div>
          <h2 class="text-xl font-bold text-gray-800 mb-2">{{ selectedProperty.title }}</h2>
          <div class="text-2xl font-bold text-red-500 mb-4">{{ selectedProperty.price }}万</div>
          
          <!-- 房源元信息 -->
          <div class="property-meta-info">
            <div class="property-meta-item">
              <i class="fa fa-arrows-alt property-meta-icon"></i>
              <div class="property-meta-label">面积</div>
              <div class="property-meta-value">{{ selectedProperty.area }}m²</div>
            </div>
            <div class="property-meta-item">
              <i class="fa fa-home property-meta-icon"></i>
              <div class="property-meta-label">户型</div>
              <div class="property-meta-value">{{ selectedProperty.type }}</div>
            </div>
            <div class="property-meta-item">
              <i class="fa fa-compass property-meta-icon"></i>
              <div class="property-meta-label">朝向</div>
              <div class="property-meta-value">{{ selectedProperty.direction }}</div>
            </div>
            <div class="property-meta-item">
              <i class="fa fa-paint-brush property-meta-icon"></i>
              <div class="property-meta-label">装修</div>
              <div class="property-meta-value">{{ selectedProperty.decoration }}</div>
            </div>
          </div>
          
          <!-- 房源特色 -->
          <div class="mb-4">
            <h3 class="font-bold text-gray-700 mb-2">房源特色</h3>
            <div class="feature-tags">
              <span v-for="feature in selectedProperty.features" :key="feature" class="tag bg-green-500">
                {{ feature }}
              </span>
            </div>
          </div>
          
          <!-- 房源描述 -->
          <div class="mb-4">
            <h3 class="font-bold text-gray-700 mb-2">房源描述</h3>
            <p class="text-gray-600">{{ selectedProperty.description }}</p>
          </div>
          
          <!-- 房源地址 -->
          <div class="mb-4">
            <h3 class="font-bold text-gray-700 mb-2">房源地址</h3>
            <p class="text-gray-600">{{ selectedProperty.address }}</p>
          </div>
          
          <!-- 操作按钮 -->
          <div class="modal-footer flex justify-end space-x-3 mt-6">
            <button 
              class="btn-outline px-4 py-2 border rounded-md text-gray-700 hover:bg-gray-100 transition-colors"
              @click="closeDetail"
            >
              关闭
            </button>
            <button 
              class="btn-primary px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors"
              @click="contactAgent"
            >
              联系经纪人
            </button>
            <button 
              :class="['btn-favorite px-4 py-2 rounded-md transition-colors', isFavorite(selectedProperty.id) ? 'bg-red-500 text-white hover:bg-red-600' : 'bg-gray-200 text-gray-700 hover:bg-gray-300']"
              @click="toggleFavorite(selectedProperty)"
            >
              <i class="fa" :class="isFavorite(selectedProperty.id) ? 'fa-heart' : 'fa-heart-o'"></i> 
              {{ isFavorite(selectedProperty.id) ? '已收藏' : '收藏' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AIFindHouseAssistant',
  data() {
    return {
      // 聊天消息
      messages: [],
      // 输入框内容
      inputMessage: '',
      // 是否正在处理
      isProcessing: false,
      // 热门推荐房源
      hotProperties: [
        {
          id: 101,
          title: '海淀区·中关村公馆',
          area: 92,
          type: '两室两厅',
          price: 430,
          district: '海淀区',
          address: '中关村南大街5号',
          direction: '南北通透',
          decoration: '精装修',
          features: ['近地铁', '学区房', '拎包入住', '南北通透'],
          description: '位于中关村核心区域，交通便利，周边配套设施齐全。房屋南北通透，采光好，装修精美，适合刚需家庭居住。',
          tags: ['推荐', '热门']
        },
        {
          id: 102,
          title: '朝阳区·三里屯SOHO',
          area: 125,
          type: '三室两厅',
          price: 580,
          district: '朝阳区',
          address: '工体北路8号',
          direction: '东南向',
          decoration: '豪装',
          features: ['高端小区', '配套完善', '交通便利', '商圈中心'],
          description: '位于朝阳区繁华商圈，周边商场、餐饮、娱乐设施一应俱全。房屋装修豪华，空间宽敞，适合追求高品质生活的家庭。',
          tags: ['豪华', '商圈']
        },
        {
          id: 103,
          title: '西城区·德胜置业广场',
          area: 86,
          type: '两室一厅',
          price: 410,
          district: '西城区',
          direction: '南向',
          address: '德胜门外大街11号',
          decoration: '简装',
          features: ['学区房', '近地铁', '配套成熟', '闹中取静'],
          description: '西城区优质学区房，周边教育资源丰富，交通便利。房屋结构合理，采光充足，适合有孩子的家庭居住。',
          tags: ['学区', '核心地段']
        },
        {
          id: 104,
          title: '东城区·东方广场',
          area: 158,
          type: '四室两厅',
          price: 820,
          district: '东城区',
          address: '东长安街1号',
          direction: '南北通透',
          decoration: '精装修',
          features: ['市中心', '交通便利', '高端物业', '配套完善'],
          description: '位于东城区核心位置，毗邻天安门广场，地理位置优越。房屋空间宽敞，装修精美，视野开阔，是不可多得的市中心豪宅。',
          tags: ['豪华', '地标']
        },
        {
          id: 105,
          title: '丰台区·丰台科技园',
          area: 78,
          type: '两室一厅',
          price: 290,
          district: '丰台区',
          address: '丰台科技园区海鹰路1号',
          direction: '东南向',
          decoration: '精装',
          features: ['近地铁', '总价低', '配套完善', '适合刚需'],
          description: '丰台区高性价比房源，交通便利，周边生活配套齐全。房屋装修精美，空间利用率高，适合首次购房的年轻人。',
          tags: ['刚需首选', '性价比高']
        }
      ],
      // 收藏的房源
      favoriteProperties: [],
      // 用户浏览历史
      browsingHistory: [],
      // 快速功能列表
      quickFeatures: [
        { id: 1, name: '按区域找房', icon: 'fa-map-marker' },
        { id: 2, name: '按价格找房', icon: 'fa-cny' },
        { id: 3, name: '按户型找房', icon: 'fa-home' },
        { id: 4, name: '学区房推荐', icon: 'fa-graduation-cap' },
        { id: 5, name: '近地铁房源', icon: 'fa-subway' },
        { id: 6, name: '新上房源', icon: 'fa-star-o' },
        { id: 7, name: '我的收藏', icon: 'fa-heart-o' },
        { id: 8, name: '浏览历史', icon: 'fa-history' }
      ],
      // 建议标签
      suggestions: [
        '海淀区两居室推荐',
        '300万以内的房子',
        '近地铁精装修',
        '学区房推荐'
      ],
      // 详情弹窗状态
      showDetail: false,
      selectedProperty: null
    };
  },
  
  mounted() {
    // 监听窗口大小变化，自动滚动到底部
    window.addEventListener('resize', this.scrollToBottom);
    
    // 从本地存储加载历史对话记录和用户数据
    this.loadChatHistory();
    this.loadFavorites();
    this.loadBrowsingHistory();
    
    // 页面加载完成后滚动到底部
    this.$nextTick(() => {
      this.scrollToBottom();
      
      // 根据浏览历史显示个性化推荐
      if (this.browsingHistory.length > 0) {
        setTimeout(() => {
          this.showPersonalizedRecommendations();
        }, 2000);
      }
    });
  },
  
  beforeUnmount() {
    window.removeEventListener('resize', this.scrollToBottom);
    // 保存对话历史到本地存储
    this.saveChatHistory();
    this.saveFavorites();
  },
  
  methods: {
    // 发送消息
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isProcessing) return;
      
      const message = this.inputMessage.trim();
      this.inputMessage = '';
      
      // 添加用户消息
      this.addMessage(message, 'user');
      
      this.scrollToBottom();
      this.isProcessing = true;
      
      // 添加AI正在输入的提示
      const loadingMessageIndex = this.messages.length;
      this.messages.push({
        from: 'ai',
        content: '',
        loading: true,
        timestamp: new Date().toISOString()
      });
      
      try {
        // 模拟AI处理时间
        await new Promise(resolve => setTimeout(resolve, 1500));
        
        // 根据用户输入生成智能回复
        const response = this.generateResponse(message);
        
        // 移除加载提示，添加AI回复
        this.messages.splice(loadingMessageIndex, 1, response);
      } catch (error) {
        // 错误处理
        this.messages.splice(loadingMessageIndex, 1, {
          from: 'ai',
          content: '抱歉，我暂时无法为您提供服务，请稍后再试。',
          timestamp: new Date().toISOString()
        });
      } finally {
        this.isProcessing = false;
        // 延迟滚动到底部，确保消息完全渲染
        setTimeout(() => {
          this.scrollToBottom();
        }, 100);
      }
    },
    
    // 添加消息到聊天记录
    addMessage(content, from) {
      this.messages.push({
        from,
        content,
        timestamp: new Date().toISOString()
      });
      this.saveChatHistory();
      this.scrollToBottom();
    },
    
    // 生成智能回复
    generateResponse(userMessage) {
      const message = userMessage.toLowerCase();
      let response = { from: 'ai', timestamp: new Date().toISOString() };
      
      // 关键词匹配逻辑
      if (message.includes('预算') || message.includes('万')) {
        // 提取价格范围
        const priceMatch = message.match(/(\d+)万/);
        if (priceMatch) {
          const maxPrice = parseInt(priceMatch[1]);
          const matchingProperties = this.hotProperties.filter(p => p.price <= maxPrice);
          
          if (matchingProperties.length > 0) {
            response.content = `为您找到${matchingProperties.length}套${maxPrice}万以内的房源：`;
            response.properties = matchingProperties;
          } else {
            response.content = `抱歉，没有找到${maxPrice}万以内的房源。您可以尝试提高预算范围。`;
          }
        } else {
          response.content = '请您告诉我具体的预算范围，我可以为您推荐合适的房源。';
        }
      } 
      else if (message.includes('两居') || message.includes('三室') || message.includes('户型')) {
        // 提取户型信息
        let typeKeyword = '';
        if (message.includes('两居') || message.includes('两室')) typeKeyword = '两室';
        else if (message.includes('三居') || message.includes('三室')) typeKeyword = '三室';
        else if (message.includes('一居') || message.includes('一室')) typeKeyword = '一室';
        else if (message.includes('四居') || message.includes('四室')) typeKeyword = '四室';
        
        if (typeKeyword) {
          const matchingProperties = this.hotProperties.filter(p => p.type.includes(typeKeyword));
          
          if (matchingProperties.length > 0) {
            response.content = `为您找到${matchingProperties.length}套${typeKeyword}户型的房源：`;
            response.properties = matchingProperties;
          } else {
            response.content = `抱歉，暂时没有找到${typeKeyword}户型的房源。`;
          }
        } else {
          response.content = '您想找几居室的房子呢？我可以为您筛选合适的房源。';
        }
      }
      else if (message.includes('海淀') || message.includes('朝阳') || message.includes('西城') || message.includes('东城') || message.includes('丰台')) {
        // 提取区域信息
        let district = '';
        if (message.includes('海淀')) district = '海淀区';
        else if (message.includes('朝阳')) district = '朝阳区';
        else if (message.includes('西城')) district = '西城区';
        else if (message.includes('东城')) district = '东城区';
        else if (message.includes('丰台')) district = '丰台区';
        
        const matchingProperties = this.hotProperties.filter(p => p.district === district);
        
        if (matchingProperties.length > 0) {
          response.content = `为您找到${matchingProperties.length}套${district}的房源：`;
          response.properties = matchingProperties;
        } else {
          response.content = `抱歉，暂时没有找到${district}的房源。`;
        }
      }
      else if (message.includes('学区房')) {
        const matchingProperties = this.hotProperties.filter(p => 
          p.features.includes('学区房') || p.tags.includes('学区')
        );
        
        if (matchingProperties.length > 0) {
          response.content = `为您找到${matchingProperties.length}套优质学区房：`;
          response.properties = matchingProperties;
        } else {
          response.content = '抱歉，暂时没有找到合适的学区房。';
        }
      }
      else if (message.includes('地铁') || message.includes('交通')) {
        const matchingProperties = this.hotProperties.filter(p => 
          p.features.includes('近地铁') || p.features.includes('交通便利')
        );
        
        if (matchingProperties.length > 0) {
          response.content = `为您找到${matchingProperties.length}套交通便利的房源：`;
          response.properties = matchingProperties;
        } else {
          response.content = '抱歉，暂时没有找到交通便利的房源。';
        }
      }
      else if (message.includes('收藏')) {
        if (this.favoriteProperties.length > 0) {
          response.content = `您有${this.favoriteProperties.length}套收藏的房源：`;
          response.properties = this.favoriteProperties;
        } else {
          response.content = '您还没有收藏任何房源。点击房源卡片上的收藏按钮可以将喜欢的房源添加到收藏列表。';
        }
      }
      else if (message.includes('历史') || message.includes('浏览')) {
        if (this.browsingHistory.length > 0) {
          response.content = `您最近浏览了${this.browsingHistory.length}套房源：`;
          response.properties = this.browsingHistory.map(item => item.property || item);
        } else {
          response.content = '您还没有浏览过任何房源。点击查看房源详情可以将其添加到浏览历史。';
        }
      }
      else {
        // 默认回复
        response.content = '感谢您的咨询！我是智慧找房助手，您可以告诉我您的具体需求，如：\n- 我想找海淀区的两居室\n- 预算300万以内的房子\n- 近地铁的学区房\n\n或者您可以点击左侧的快速功能按钮获取推荐。';
      }
      
      return response;
    },
    
    // 使用建议标签
    useSuggestion(suggestion) {
      this.inputMessage = suggestion;
      this.sendMessage();
    },
    
    // 处理快速功能点击
    handleQuickFeature(feature) {
      let message = '';
      
      switch (feature.id) {
        case 1: message = '我想按区域找房，请推荐各区域的热门房源'; break;
        case 2: message = '我想按价格找房，请推荐不同价位的房源'; break;
        case 3: message = '我想按户型找房，请推荐各种户型的房源'; break;
        case 4: message = '请推荐优质学区房'; break;
        case 5: message = '请推荐近地铁的房源'; break;
        case 6: message = '请推荐最新上线的房源'; break;
        case 7: message = '查看我的收藏房源'; break;
        case 8: message = '查看我的浏览历史'; break;
        default: message = '请问有什么可以帮到您？';
      }
      
      this.addMessage(message, 'user');
      this.sendMessageSimulation(message);
    },
    
    // 模拟发送消息
    async sendMessageSimulation(message) {
      this.isProcessing = true;
      
      const loadingMessageIndex = this.messages.length;
      this.messages.push({
        from: 'ai',
        content: '',
        loading: true,
        timestamp: new Date().toISOString()
      });
      
      try {
        await new Promise(resolve => setTimeout(resolve, 1000));
        const response = this.generateResponse(message);
        this.messages.splice(loadingMessageIndex, 1, response);
      } catch (error) {
        this.messages.splice(loadingMessageIndex, 1, {
          from: 'ai',
          content: '抱歉，我暂时无法为您提供服务，请稍后再试。',
          timestamp: new Date().toISOString()
        });
      } finally {
        this.isProcessing = false;
        setTimeout(() => {
          this.scrollToBottom();
        }, 100);
      }
    },
    
    // 显示房源详情
    showPropertyDetail(property) {
      this.selectedProperty = property;
      this.showDetail = true;
      // 添加到浏览历史
      this.addToBrowsingHistory(property);
    },
    
    // 关闭详情弹窗
    closeDetail() {
      this.showDetail = false;
      this.selectedProperty = null;
    },
    
    // 联系经纪人
    contactAgent() {
      this.closeDetail();
      this.addMessage('正在为您转接经纪人，请稍候...', 'ai');
      setTimeout(() => {
        this.addMessage('经纪人李小姐（电话：13812345678）将在5分钟内与您联系。', 'ai');
      }, 2000);
    },
    
    // 切换收藏状态
    toggleFavorite(property) {
      const index = this.favoriteProperties.findIndex(p => p.id === property.id);
      if (index > -1) {
        this.favoriteProperties.splice(index, 1);
        this.addMessage('已取消收藏该房源', 'ai');
      } else {
        this.favoriteProperties.push(property);
        this.addMessage('已收藏该房源', 'ai');
      }
      this.saveFavorites();
    },
    
    // 检查是否已收藏
    isFavorite(propertyId) {
      return this.favoriteProperties.some(p => p.id === propertyId);
    },
    
    // 添加到浏览历史
    addToBrowsingHistory(property) {
      // 检查数据有效性
      if (!property || !property.id) {
        console.warn('无效的房源数据');
        return;
      }
      
      // 移除可能存在的重复项（考虑嵌套结构）
      this.browsingHistory = this.browsingHistory.filter(item => {
        const itemProperty = item.property || item;
        return itemProperty.id !== property.id;
      });
      
      // 添加到历史记录开头，使用统一的格式
      this.browsingHistory.unshift({
        property: property,
        timestamp: new Date().toISOString()
      });
      
      // 限制历史记录数量
      if (this.browsingHistory.length > 20) {
        this.browsingHistory = this.browsingHistory.slice(0, 20);
      }
      
      // 保存到本地存储
      this.saveBrowsingHistory();
    },
    
    // 保存浏览历史
    saveBrowsingHistory() {
      try {
        localStorage.setItem('browsingHistory', JSON.stringify(this.browsingHistory));
      } catch (error) {
        console.warn('无法保存浏览历史:', error);
      }
    },
    
    // 加载浏览历史
    loadBrowsingHistory() {
      try {
        const savedHistory = localStorage.getItem('browsingHistory');
        if (savedHistory) {
          const parsed = JSON.parse(savedHistory);
          // 确保返回的是数组
          this.browsingHistory = Array.isArray(parsed) ? parsed : [];
        }
      } catch (error) {
        console.warn('无法加载浏览历史:', error);
        this.browsingHistory = [];
      }
    },
    
    // 保存聊天历史到本地存储
    saveChatHistory() {
      try {
        localStorage.setItem('aiChatHistory', JSON.stringify(this.messages));
      } catch (error) {
        console.warn('无法保存聊天历史:', error);
      }
    },
    
    // 从本地存储加载聊天历史
    loadChatHistory() {
      try {
        const savedHistory = localStorage.getItem('aiChatHistory');
        if (savedHistory) {
          const parsedHistory = JSON.parse(savedHistory);
          // 只加载最近的20条消息，避免页面过于臃肿
          this.messages = parsedHistory.slice(-20);
        }
      } catch (error) {
        console.warn('无法加载聊天历史:', error);
        // 如果加载失败，保持默认的欢迎消息
      }
    },
    
    // 清空聊天历史
    clearChatHistory() {
      this.messages = [];
      localStorage.removeItem('aiChatHistory');
      this.scrollToBottom();
      this.addMessage('聊天历史已清空', 'ai');
    },
    
    // 加载收藏列表
    loadFavorites() {
      try {
        const savedFavorites = localStorage.getItem('favoriteProperties');
        if (savedFavorites) {
          this.favoriteProperties = JSON.parse(savedFavorites);
        }
      } catch (error) {
        console.warn('无法加载收藏:', error);
      }
    },
    
    // 保存收藏列表
    saveFavorites() {
      try {
        localStorage.setItem('favoriteProperties', JSON.stringify(this.favoriteProperties));
      } catch (error) {
        console.warn('无法保存收藏:', error);
      }
    },
    
    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const chatContainer = this.$el.querySelector('.chat-messages');
        if (chatContainer) {
          chatContainer.scrollTop = chatContainer.scrollHeight;
        }
      });
    },
    
    // 显示个性化推荐
    showPersonalizedRecommendations() {
      // 根据浏览历史分析用户偏好
      const districts = {};
      const types = {};
      
      this.browsingHistory.forEach(item => {
        const property = item.property || item;
        if (property) {
          districts[property.district] = (districts[property.district] || 0) + 1;
          types[property.type] = (types[property.type] || 0) + 1;
        }
      });
      
      // 找出最常浏览的区域和户型
      let favoriteDistrict = '';
      let favoriteType = '';
      let maxDistrictCount = 0;
      let maxTypeCount = 0;
      
      for (const [district, count] of Object.entries(districts)) {
        if (count > maxDistrictCount) {
          maxDistrictCount = count;
          favoriteDistrict = district;
        }
      }
      
      for (const [type, count] of Object.entries(types)) {
        if (count > maxTypeCount) {
          maxTypeCount = count;
          favoriteType = type;
        }
      }
      
      // 根据偏好生成推荐
      let recommendations = this.hotProperties;
      let recommendationText = '根据您的浏览历史，为您推荐以下房源：';
      
      if (favoriteDistrict && favoriteType) {
        recommendations = this.hotProperties.filter(p => 
          p.district === favoriteDistrict || p.type === favoriteType
        );
        recommendationText = `根据您的浏览历史，发现您可能对${favoriteDistrict}和${favoriteType}感兴趣，为您推荐：`;
      } else if (favoriteDistrict) {
        recommendations = this.hotProperties.filter(p => p.district === favoriteDistrict);
        recommendationText = `根据您的浏览历史，发现您可能对${favoriteDistrict}感兴趣，为您推荐：`;
      } else if (favoriteType) {
        recommendations = this.hotProperties.filter(p => p.type === favoriteType);
        recommendationText = `根据您的浏览历史，发现您可能对${favoriteType}感兴趣，为您推荐：`;
      }
      
      // 如果找到匹配的推荐
      if (recommendations.length > 0) {
        this.addMessage(recommendationText, 'ai');
        setTimeout(() => {
          this.addMessage('', 'ai');
          this.messages[this.messages.length - 1].properties = recommendations;
        }, 500);
      }
    }
  }
};
</script>

<style scoped>
.ai-customer-service-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

/* 头部样式 */
.ai-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 2rem;
  background-color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.ai-logo {
  display: flex;
  align-items: center;
}

.ai-status {
  display: flex;
  align-items: center;
}

.online-indicator {
  width: 8px;
  height: 8px;
  background-color: #10b981;
  border-radius: 50%;
  margin-right: 6px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 1;
  }
}

/* 主要内容区样式 */
.ai-main {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 侧边栏样式 */
.ai-sidebar {
  width: 280px;
  padding: 1rem;
  overflow-y: auto;
  background-color: #f9fafb;
  border-right: 1px solid #e5e7eb;
}

.feature-card,
.hot-properties {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.feature-btn {
  transition: all 0.2s ease;
}

.feature-btn:hover {
  transform: translateX(2px);
}

.property-list {
  max-height: 300px;
  overflow-y: auto;
}

.property-item {
  border-bottom: 1px solid #f3f4f6;
  transition: background-color 0.2s ease;
}

.property-item:last-child {
  border-bottom: none;
}

/* 聊天区域样式 */
.ai-chat {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: white;
}

.chat-messages {
  flex: 1;
  padding: 2rem;
  overflow-y: auto;
  background-color: #f8fafc;
}

.message {
  margin-bottom: 1.5rem;
}

.ai-message .message-content {
  background-color: white;
  color: #374151;
  border-radius: 18px 18px 18px 4px;
  padding: 1rem;
  max-width: 70%;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  border: 1px solid #e5e7eb;
}

.user-message {
  display: flex;
  justify-content: flex-end;
}

.user-message .message-content {
  background-color: #3b82f6;
  color: white;
  border-radius: 18px 18px 4px 18px;
  padding: 1rem;
  max-width: 70%;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

/* 加载动画 */
.loading-indicator {
  padding: 0.5rem 0;
}

.typing-dots {
  display: inline-flex;
  align-items: center;
}

.dot {
  width: 8px;
  height: 8px;
  background-color: #9ca3af;
  border-radius: 50%;
  margin: 0 2px;
  animation: typing 1.4s infinite both;
}

.dot:nth-child(2) {
  animation-delay: 0.2s;
}

.dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.3;
  }
  30% {
    transform: translateY(-4px);
    opacity: 1;
  }
}

/* 房源推荐样式 */
.property-recommendations {
  margin-top: 1rem;
}

.properties-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 1rem;
  margin-top: 0.5rem;
}

.property-card {
  border: 1px solid #e5e7eb;
  transition: all 0.3s ease;
}

.property-card:hover {
  transform: translateY(-2px);
  border-color: #3b82f6;
}

/* 输入区域样式 */
.chat-input-area {
  border-top: 1px solid #e5e7eb;
}

.input-toolbar {
  background-color: white;
}

.toolbar-btn {
  padding: 0.5rem;
  border: none;
  background: none;
  cursor: pointer;
  transition: all 0.2s ease;
}

.toolbar-btn:hover {
  transform: scale(1.1);
}

.suggestions {
  border-bottom: 1px solid #e5e7eb;
}

.suggestion-tag {
  transition: all 0.2s ease;
}

.suggestion-tag:hover {
  transform: translateY(-1px);
}

.input-container {
  background-color: white;
}

.send-button {
  transition: all 0.2s ease;
}

.send-button:hover:not(:disabled) {
  transform: scale(1.05);
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  max-width: 900px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

.modal-header {
  padding: 1.5rem;
  border-bottom: 1px solid #e5e7eb;
}

.modal-body {
  padding: 1.5rem;
}

.modal-footer {
  padding: 1rem 1.5rem;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: flex-end;
  gap: 0.75rem;
}

/* 详情页样式 */
.property-detail-image {
  position: relative;
  border-radius: 0.75rem;
  overflow: hidden;
}

.detail-item {
  display: flex;
  padding: 0.75rem 0;
  border-bottom: 1px solid #f3f4f6;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-label {
  width: 80px;
  flex-shrink: 0;
  font-weight: 500;
  color: #6b7280;
}

.detail-value {
  color: #374151;
  font-weight: 400;
}

.feature-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.75rem;
  flex: 1;
}

/* 房源详情页的元信息样式 */
.property-meta-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 1rem;
  margin: 1.5rem 0;
  padding: 1rem;
  background-color: #f9fafb;
  border-radius: 0.75rem;
}

.property-meta-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.property-meta-icon {
  font-size: 1.5rem;
  color: #3b82f6;
  margin-bottom: 0.5rem;
}

.property-meta-label {
  font-size: 0.875rem;
  color: #6b7280;
}

.property-meta-value {
  font-size: 1rem;
  font-weight: 600;
  color: #1f2937;
  margin-top: 0.25rem;
}

.property-detail-image .property-tags {
  position: absolute;
  top: 1rem;
  left: 1rem;
  z-index: 10;
  display: flex;
  gap: 0.75rem;
}

.tag {
  font-size: 0.75rem;
  font-weight: 500;
  padding: 0.4rem 0.75rem;
  border-radius: 1.25rem;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  color: white;
}

.tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.close-button {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0.25rem;
  font-size: 1.25rem;
  transition: color 0.2s ease;
}

.btn-outline {
  transition: all 0.2s ease;
}

.btn-outline:hover {
  background-color: #f3f4f6;
}

.btn-primary {
  transition: all 0.2s ease;
}

.btn-primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 6px rgba(59, 130, 246, 0.2);
}

.btn-favorite {
  transition: all 0.2s ease;
}

.btn-favorite:hover {
  transform: translateY(-1px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ai-main {
    flex-direction: column;
  }
  
  .ai-sidebar {
    width: 100%;
    max-height: 200px;
    order: 2;
  }
  
  .ai-chat {
    order: 1;
  }
  
  .properties-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
  
  .ai-message .message-content,
  .user-message .message-content {
    max-width: 90%;
  }
  
  .modal-content {
    width: 95%;
    margin: 1rem;
  }
}
</style>